package core.proto;

//import app.constants.CollabVizConstants;
import app.exceptions.CollabVizException;
import app.util.PropertyLoaderUtil;

import javax.swing.*;

import org.apache.commons.io.FilenameUtils;

import com.oreilly.servlet.HttpMessage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;
import java.util.Properties;

import static app.constants.CollabVizConstants.*;
public class InfoViz extends JApplet {
	/**
	 *
	 */
	static final String SEPARATOR = "SEPARATORFORSERVLET";

	private static URL codebase;

	private static final long serialVersionUID = 1L;
	public static String UserID;

	int contentPaneHeight;


	JTextField nick;

	JComboBox viewList;

	JCheckBox screenCapOption;

	public static URL codebase(){
		return codebase;
	}

	public void init() {
		try {

			new File(LOCAL_DIRECTORY).mkdir();
			new File(LOG_FOLDER).mkdir();
			new File(NOTE_FOLDER).mkdir();
			new File(NOTEPAD_HIGHLIGHT_FOLDER).mkdir();

			codebase = getCodeBase();


			//			core.proto.FileDownload.Download("img.zip");
			if (! new File(FilenameUtils.concat(LOCAL_DIRECTORY, "HTML")).exists()){
				core.proto.FileDownload.Download("HTML.zip");
			}
			if (! new File(FilenameUtils.concat(LOCAL_DIRECTORY, "index")).exists()){
				core.proto.FileDownload.Download("index.zip");		// this doesn't work on local machine. wtf. 	
			}
			SwingUtilities.invokeAndWait( new Runnable() {
				public void run() {
					UserID = "Default_User";
					JPanel uploadPanel = new JPanel( new FlowLayout( FlowLayout.CENTER ) );
					uploadPanel.setSize( WINDOW_WIDTH, WINDOW_HEIGHT);
					nick = new JTextField(20);
					uploadPanel.add(nick);
					//create the upload button but don't add it yet.
					final JButton startButton = new JButton( "Start" );
					startButton.addActionListener( new StartButtonHandler() );
					uploadPanel.add( startButton );

					String[] viewStrings = { "Complete View", "No Viz View", "No Notes View", "No Viz/Notes View" };

					//Create the combo box, select item at index 4.
					//Indices start at 0, so 4 specifies the pig.
					viewList = new JComboBox( viewStrings );
					viewList.setSelectedIndex( 0 );
					screenCapOption = new JCheckBox( "Enable Screen Capture" );
					uploadPanel.add( viewList );
					uploadPanel.add( screenCapOption );
					add( uploadPanel );
					setSize( WINDOW_WIDTH, WINDOW_HEIGHT );
				}
			} );
		} catch( Exception e ) {
			throw new Error(e);
		}
	}

	public void destroy() {
		try {
			uploadFile(getCodeBase());
		} catch (CollabVizException e) {
			e.printStackTrace();
		}

	}

	public static void uploadFile(URL u) throws CollabVizException { 
		String logFolder = LOG_FOLDER;
		String date = Util.logDateFormat.format(Util.logFileCreationTime);
		String fileName1 = "syslog-"+"null"+"-"+date+".txt";
		String filePath1 = logFolder+"/"+fileName1;
		File f1 = new File(filePath1);
		StringBuffer s = new StringBuffer();
		//System.out.println(SEPARATOR);
		s.append(fileName1+SEPARATOR);
		try {
			BufferedReader in = new BufferedReader(new FileReader(f1));
			String str;
			while ((str = in.readLine()) != null) {
				s.append(str);
			}
			in.close();
		} catch (IOException e) {
		}
		s.append(SEPARATOR);
		String fileName2 = "userlog-"+UserID+"-"+date+".txt";
		String filePath2 = logFolder+"/"+fileName2;
		File f2 = new File(filePath2);
		s.append(fileName2+SEPARATOR);
		try {
			BufferedReader in = new BufferedReader(new FileReader(f2));
			String str;
			while ((str = in.readLine()) != null) {
				s.append(str);
			}
			in.close();
		} catch (IOException e) {
		}
		try { 
			URL url = new URL(u, "/CollabVizUploader/uploader"); 
			HttpMessage msg = new HttpMessage(url); 
			Properties props = new Properties(); 
			props.put("message", s.toString()); 
			msg.sendPostMessage(props); 
		} catch (SocketException e) { 
			// Can't connect to host, report it and abandon the broadcast 
			System.out.println("Can't connect to host: " + e.getMessage()); 
		} catch (FileNotFoundException e) { 
			// Servlet doesn't exist, report it and abandon the broadcast 
			System.out.println("Resource not found: " + e.getMessage()); 
		} catch (Exception e) { 
			// Some other problem, report it and abandon the broadcast 
			System.out.println("General exception: " + e.getClass().getName() + ": " + e.getMessage());
		}
	} 

	private class StartButtonHandler implements ActionListener {

		@Override
		public void actionPerformed( ActionEvent arg0 ) {
			final String prompt = "Please enter a nick name";
			try {
				String txt = nick.getText().trim();
				if(! txt.equals("") && ! txt.equals(prompt)) {
					UserID = nick.getText();
					getContentPane().removeAll();
					setSize( WINDOW_WIDTH, WINDOW_HEIGHT );

					getContentPane().add( new AllComponents( viewList.getSelectedIndex(),
							screenCapOption.isSelected() ) );
				}
				else {
					nick.setText(prompt);
				}

			} catch( IOException e ) {
				e.printStackTrace();
			} catch( CollabVizException e ) {
				e.printStackTrace();
			}
		}

	}
}
